<template>
  <div class="alloc-menu">
    <el-card>
      <div slot="header" class="clearfix">
        <span>分配权限</span>
      </div>
      <el-tree
        ref="menu-tree"
        :data="menus"
        node-key="id"
        :props="defaultProps"
        :default-checked-keys="checkKeys"
        show-checkbox
        default-expand-all
      ></el-tree>

      <div>
        <el-button @click="resetChecked">清空</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import {
  getMenuNodeList,
  allocateRoleMenus,
  getRoleMenus,
} from "@/services/menu";
import { Tree } from "element-ui";
export default Vue.extend({
  name: "AllocMenuIndex",
  props: {
    roleId: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      menus: [],
      defaultProps: {
        children: "subMenuList",
        label: "name",
      },
      checkKeys: [],
    };
  },
  created() {
    this.loadMenus();
    this.loadRoleMenus();
  },
  methods: {
    async loadMenus() {
      const { data } = await getMenuNodeList();
      this.menus = data.data;
    },
    async loadRoleMenus() {
      const { data } = await getRoleMenus(this.roleId);
      this.getCheckedKeys(data.data);
    },
    getCheckedKeys(menus: any[]) {
      menus.forEach((menu: any) => {
        if (menu.selected && !menu.subMenuList) {
          this.checkKeys = [...(this.checkKeys as never), menu.id] as any;
        }
        if (menu.subMenuList) {
          this.getCheckedKeys(menu.subMenuList);
        }
      });
    },
    async onSave() {
      const menuIdList = (this.$refs["menu-tree"] as Tree).getCheckedKeys();
      await allocateRoleMenus({
        roleId: this.roleId,
        menuIdList,
      });
      this.$message.success("操作成功");
      this.$router.back();
    },
    resetChecked() {
      (this.$refs["menu-tree"] as Tree).setCheckedKeys([]);
    },
  },
});
</script>

<style lang="scss" scoped>
</style>